import { createStore } from 'vuex'
import { login, register, logout, getProfile } from '@/api/auth'
import router from '@/router'

export default createStore({
  state: {
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user')) || null
  },
  
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER(state, user) {
      state.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },
    CLEAR_AUTH(state) {
      state.token = ''
      state.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    }
  },
  
  actions: {
    async login({ commit }, loginData) {
      try {
        const response = await login(loginData)
        console.log('Login response:', response)
        
        const { token, user } = response
        
        commit('SET_TOKEN', token)
        commit('SET_USER', user)
        
        // 根据用户角色跳转
        switch (user.role) {
          case 'ADMIN':
            router.push('/admin/dashboard')
            break
          case 'TEACHER':
            router.push('/teacher/dashboard')
            break
          case 'STUDENT':
            router.push('/student/dashboard')
            break
          default:
            router.push('/')
        }
        
        return response
      } catch (error) {
        console.error('Login error:', error)
        throw error
      }
    },
    
    async register(_, registerData) {
      const response = await register(registerData)
      router.push('/login')
      return response
    },

    async logout({ commit }) {
      try {
        await logout()
        commit('CLEAR_AUTH')
        router.push('/login')
      } catch (error) {
        console.error('Logout failed:', error)
      }
    },
    
    async getProfile({ commit }) {
      try {
        const response = await getProfile()
        commit('SET_USER', response.data)
        return response
      } catch (error) {
        console.error('Get profile failed:', error)
        throw error
      }
    }
  }
}) 